var express = require('express');
var router = express.Router();
const mongodb= require('../components/mongo');

const multer = require('multer');
const uploader = multer({dest:'uploads/'});

/* GET home page. */
router.get('/',async function(req, res, next) {
   console.log(req.query);
   var m_type = req.query.type;
   var m_mode = req.query.mode;
   
   if( m_type == undefined || m_type <= 0 || m_type > 5){
	   //type == 0 or not exist
	   const result = await mongodb.find("Article",{});
	   if(result.length>0){

		   var m_articles = sortByMode(result,m_mode);   
		   //end sort
		   
		   for(index in m_articles){
			   var hot = m_articles[index].supports.length + m_articles[index].comments.length;
			   console.log(m_articles[index].time_stamp + '=== hot : ' + hot);
		   }
	   	   res.json({
	   		   errno:0,
	   		   errmsg:"",
	   		   data:{
	   			   res:true,
	   			   articles:m_articles,
	   		   },
	   		   });
	   }else{
	   	   res.json({
	   	      errno:0,
	   	      errmsg:"",
	   	      data:{res:false},
	   	      });
	   }
   }else{
	   // with type = 1,2,3,4,5
	   const result = await mongodb.find("Article",{type:m_type});
	   if(result.length>0){
		   var m_articles = sortByMode(result,m_mode);	   
		   //end sort
		   for(index in m_articles){
			   var hot = m_articles[index].supports.length + m_articles[index].comments.length;
			   console.log(m_articles[index].time_stamp + '=== hot : ' + hot);
		   }
	   	   res.json({
	   		   errno:0,
	   		   errmsg:"",
	   		   data:{
	   			   res:true,
	   			   articles:m_articles,
				},
	   		   });
	   }else{
	   	   res.json({
	   	      errno:0,
	   	      errmsg:"",
	   	      data:{res:false},
	   	      });
	   }
   }
   
});

var sortByMode = function(articles,mode){
		
	if(mode == "hot"){
		articles.sort(function(a,b){
			var hot_a = a.comments.length + a.supports.length;
			var hot_b = b.comments.length + b.supports.length;
			return hot_b - hot_a;
		})
	}else{
		articles.sort(function(a,b){
			var ta = a.time_stamp;
			var tb = b.time_stamp;
			return Date.parse(tb) - Date.parse(ta);
		})
	}
	return articles;
}


module.exports = router;